import authorize from '../../utils/authorize.js';
import sports from '../../services/sports.js';
import service_conch from '../../services/conch';
import Router from '../../utils/router.js';
import Record from '../../utils/page-record.js';
import md5 from '../../utils/md5.js';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    linedata: [
      '1、步数每日清零；', '2、每满1000步即可兑换贝壳；', '3、100步可兑换1贝壳（四舍五入）；', '4、每天可兑换多次；', '5、兑换上限：150贝壳/天；', '6、每日首次兑换步数，可获得一次抽奖机会。'
    ],
    mask: false, //遮罩
    guize: false, //活动规则
    dui: false, //兑换弹框
    cheng: false, //兑换成功
    thousand: false, //不足一千步的提示
    enough: false, //已经兑换了150贝壳
    auth: 2, //是否授权微信运动权限
    conch: 0, //可兑换贝壳数
    step: 0, //步数
    conch_numed: '', //已经兑换总的贝壳 判断不超150贝壳
    getconchs: '', //本次兑换的贝壳数量
    all_step: '', //总步数
    datas: [], //贝壳商品
    loadBloon: true,
    endBloon: true,
    pages: 0,
    noMore: true,
    store_id: '', //店铺id
    transmit: {
      style: 'position:absolute;background:red;width:100%;height:100%;left:0;top:0;opacity:0;',
      value: ''
    },
    types: 1, //执行onload 还是onshow
    phone: false, //判断是什么类型的手机
    code:'',//判断150
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    var auth = wx.getStorageSync("user_info").info_authorize;
    var user_info = wx.getStorageSync("user_info") || { id: '', lastView: { seid: '' } };
    if (user_info.lastView.seid) {
      this.setData({
        store_id: user_info.lastView.seid,
        user_id: user_info.id
      })
    }
    if (auth == 1) {
      this.setData({
        auth: 0,
      })
      var _this = this;
      setTimeout(() => {
        _this.setData({
          types: 2
        })
      }, 500)
      this.getAuth();
      console.log('onload')
    } else {
      this.setData({
        auth: 2
      })
    }
    this.createHtml(1);
    wx.getSystemInfo({
      success: function(res) {
        console.log(res.model)
        if (res.model.indexOf('iPhone') != -1) {
          _this.setData({
            phone: true
          })
        }
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  showMail() { //显示活动规则
    this.setData({
      mask: true,
      guize: true
    })
  },
  hideGuize() { //隐藏活动规则
    this.setData({
      mask: false,
      guize: false
    })
  },
  hideDui() {
    this.setData({
      mask: false,
      dui: false
    })
  },
  hideAll() { //隐藏所有
    this.setData({
      mask: false,
      guize: false,
      dui: false,
      cheng: false
    })
  },
  getAuth() { //获得微信步数授权
    var _this = this;
    authorize('werun', (b) => { //微信授权
      if (b) {
        _this.setData({
          auth: 1
        })
        wx.getWeRunData({
          success(res) {
            console.log(res)
            let param = {
              encrypted_data: res.encryptedData,
              iv: res.iv
            }
            sports.getstep(param, res => {
              if (res.code == 200) {
                _this.setData({
                  conch: res.data.conch,
                  step: _this.toThousands(Number(res.data.step)),
                  all_step: res.data.all_step,
                  conch_numed: res.data.conch_num
                })
              } else if (res.code == 415) {
                _this.setData({
                  code:415,
                  conch: res.data.conch,
                  step: _this.toThousands(Number(res.data.step)),
                  all_step: res.data.all_step,
                  conch_numed: res.data.conch_num
                })
              }

            })
          }
        })
      }
    });
  },
  getConch() { //兑换贝壳前判断
    var _this = this;
    var step = _this.data.step.toString().replace(/\,/g, '');
    if (this.data.code==415) {
      this.setData({
        enough: true
      })
      setTimeout(function() {
        _this.setData({
          enough: false
        })
      }, 1800)
      return false;
    } else if (step < 1000) {
      this.setData({
        thousand: true
      })
      setTimeout(function() {
        _this.setData({
          thousand: false
        })
      }, 1800)
      return false;
    }
    
    this.setData({
      mask: true,
      dui: true
    })
  },
  goConch() { //进行兑换
    this.hideAll();
    let _this = this;
    var timestamp = new Date().getTime();
    var step = _this.data.step.toString().replace(/\,/g, '');
    console.log(step)
    var user_salt = timestamp.toString().slice(-6) + step + this.data.conch + this.data.all_step;
    console.log(user_salt)
    user_salt = md5(user_salt)
    let param = {
      step_num: step,
      conch_num: this.data.conch,
      all_step: this.data.all_step,
      timestamp: timestamp,
      user_salt: user_salt
    }
    sports.getstepconch(param, res => {
      if (res.code == 200) {
        if (res.data.step_prize != 1) {
          _this.setData({
            cheng: true,
            mask: true,
            getconchs: res.data.conch
          })
        }
        this.getAuth();
        if (res.data.step_prize == 1) {
          wx.showModal({
            title: '抽奖提醒',
            content: '已成功将' + res.data.conch + '贝壳收入囊中!\r\n恭喜您!获得一次免费抽奖机会!',
            confirmText: '去抽奖',
            cancelText: '一会再抽',
            success(res) {
              if (res.confirm) {
                Router.go('luck', `store_id=${_this.data.store_id}`)
              }
            }
          })
        }
      } else if (res.code == 413) {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  onGotUserInfo(e) { //授权基本信息
    let _this = this;
    console.log(e)
    if (e.detail.errMsg == 'getUserInfo:ok') {
      _this.setData({
        auth: 0,
      })
    }
  },
  routerConchs() { //去往签到页
    let _this = this;
    let p = getCurrentPages().pop();
    Record.clickButton(p, 'more_shells');
    Router.go('dailytasks',``);
  },
  routerMy() { //去往我的贝壳
    Router.go('linprice',``);
  },
  //监听页面高度
  scrollTimer: null,
  onPageScroll: function(e) {
    let that = this;
    if (that.scrollTimer) {
      clearTimeout(that.scrollTimer)
    };
    that.scrollTimer = setTimeout(() => {
      that.setData({
        scrolltop: e.scrollTop
      })
    }, 500);
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var auth = wx.getStorageSync("user_info").info_authorize;
    var _this = this;
    if (auth == 1) {
      this.setData({
        auth: 0
      })
      console.log('onshow')
      if (this.data.types != 1) {
        _this.getAuth();
      }

    }

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.getAuth()
    wx.stopPullDownRefresh()
  },
  toThousands(num) { //处理展示的数字
    return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
  },
  createHtml(page) { //显示商品
    let _this = this;
    let param = {
      limit: 20,
      offset: page
    };
    service_conch.getConchGoods(param, res => {
      if (res.code == 200) {
        let stolist = _this.data.datas.concat(res.data.list);
        try {
          stolist.forEach((item, index) => {
            item.goods_pic = []
            item.goods_pic[0] = { url: item.src }
          })
        } catch (e) { }
        _this.setData({
          datas: stolist,
          pages: page + 1,
          endBloon: true,
        })
        if (stolist.length >= res.data.count) {
          _this.setData({
            loadBloon: false,
            noMore: false
          })
        }
      }
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    let that = this;
    if (that.data.loadBloon && that.data.endBloon) {
      that.setData({
        endBloon: false
      })
      that.createHtml(that.data.pages);
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    if (res.form === 'button') {
      console.log(res.target)
    }
    
    var paths = 'pages/store/index?to=' + encodeURIComponent('/pages/sports/sports') + '&store_id=' + this.data.store_id + '&sharerecord=conchcard' + '&user_id=' + this.data.user_id;

    return {
      title: '你的每一步都有价值！',
      path: paths,
      imageUrl: 'https://kpxd.zhengdianhaohuo.com/kpxd_mp/asset/sports/shares.jpg'
    }
  }

})